﻿using Lee.Models;
using Lee.Models.Entities;
using Lee.Utility.Extensions;
using Lee.Utility.Security;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using System.Collections.Concurrent;
using System.Diagnostics;
using WebA.Admin.Contracts; 
using WebApiA.Attributes; 

namespace WebApiA.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class DemoController : ControllerBase
    {
        private readonly ILogger<DemoController> _logger;  
        private readonly IServiceProvider _provider;
        private readonly IEmployeeContract _employeeContract;
        public DemoController(ILogger<DemoController> logger, IHost host, IEmployeeContract employeeContract)
        {
            _logger = logger;
            _provider = host.Services;
            _employeeContract = employeeContract;
        }

        //private IEmployeeContract _employeeContract => _provider.GetRequiredService<IEmployeeContract>();
        private ITestContract _testContract => _provider.GetRequiredService<ITestContract>();
        private IEmployeeContract _systemContract2 => GlobalConfig.ServiceProvider.GetRequiredService<IEmployeeContract>();

        /// <summary>
        /// 测试demo
        /// 
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Route("GetEmployeeList")]
        public async Task<IActionResult> GetEmployeeList()
        {
            //TaskFactory tf = new TaskFactory();
            //for (int i = 0; i < 10; i++)
            //{
            //    await tf.StartNew(getempAsync);
            //}

        
            for (int i = 0; i < 50; i++)
            {
                await getempAsync();
            }

            //var list2 =  _employeeContract.GetEmployees();

            //await Task.Delay(1000);

            var list =  await _employeeContract.FindEmployeeListAsync();
             
             return Ok(new { data= list });
             
        }

        [HttpGet]
        [Route("GetEmployeeList2")]
        public IActionResult GetEmployeeList2()
        {
            //TaskFactory tf = new TaskFactory();
            //for (int i = 0; i < 10; i++)
            //{
            //    tf.StartNew(getemp);
            //}


            for (int i = 0; i < 50; i++)
            {
                getemp();
            } 
            var list = _employeeContract.GetEmployees();

            return Ok(new { data = list });

        }
 
        private async Task getempAsync()
        {
            LogHelper.Info("TaskFactory当前进程id = " + Environment.ProcessId.ToString() + Environment.CurrentManagedThreadId.ToString());
            LogHelper.Info("TaskFactory当前线程id = " + Thread.CurrentThread.ManagedThreadId.ToString());


            _logger.LogWarning("TaskFactory当前进程id = " + Environment.ProcessId.ToString() + Environment.CurrentManagedThreadId.ToString());
            _logger.LogWarning("TaskFactory当前线程id = " + Thread.CurrentThread.ManagedThreadId.ToString());
            var list=  await _employeeContract.FindEmployeeListAsync();
            _logger.LogWarning("list========" + list.Count().ToString());
        }

        private void getemp()
        {
            LogHelper.Info("TaskFactory当前进程id = " + Environment.ProcessId.ToString() + Environment.CurrentManagedThreadId.ToString());
            LogHelper.Info("TaskFactory当前线程id = " + Thread.CurrentThread.ManagedThreadId.ToString());


            _logger.LogWarning("TaskFactory当前进程id = " + Environment.ProcessId.ToString() + Environment.CurrentManagedThreadId.ToString());
            _logger.LogWarning("TaskFactory当前线程id = " + Thread.CurrentThread.ManagedThreadId.ToString());
            var list = _employeeContract.GetEmployees();
            _logger.LogWarning("list========" + list.Count().ToString());
        }
        /// <summary>
        /// 测试demo
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Route("Get")]
        public IActionResult Get()
        {
            var list = _employeeContract.GetEmployees();
            foreach (var item in list)
            {
                var aa = item.EmployeeStatus.ToDescription();
                Console.WriteLine(aa);
                _logger.LogInformation(aa);
            }

            var aaw =new ConcurrentDictionary<int, string>(); 
            var path = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/flowdata.json");

            //var josnData = JsonSerializer.Serialize(list);
            var josnData = JsonConvert.SerializeObject(list);

            return Ok(new {msg="",code=200, data = list,josnData= josnData });
        }

        /// <summary>
        /// 测试禁止重复提交demo
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Route("PostTest")]
        [PreventDoublePost] 
        public IActionResult PostTest(int Id)
        {  
            return Ok(new { Id });
        }

        /// <summary>
        /// 测试新增人员信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Route("AddEmployee")]
        public IActionResult AddEmployee(string name)
        {  
              
            Employee emp= new  Employee();
            emp.Name = name; 
            emp.EmployeeName = name;
            emp.EmployeeSerialNumber = "123456";
            emp.Department = 1;
            emp.EmployeeStatus = EmployeeStatus.PendingStatus;
            emp.Phone = "15225074031";
            emp.BankCard = "15225074031";
            emp.WebToken = "12345";
            emp.ApiToken = "12345";
            emp.ExpirationDateUtc = DateTime.Now;
            emp.CreateTime = DateTime.Now;
            var result =  _employeeContract.SaveEntity(emp);


            return Ok(result);
        }
        /// <summary>
        ///CreateEmployee 测试新增人员信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Route("CreateEmployee")]
        public void CreateEmployee()
        {
            Random rd = new Random();
            Employee emp = new Employee();
            emp.Name = "张三" + rd.Next(99);
            emp.EmployeeName = "张三" + rd.Next(99);
            emp.EmployeeSerialNumber = rd.Next(1000, 9999).ToString();
            emp.Department = rd.Next(5);
            emp.Phone = "1522507" + rd.Next(10000, 99999);
            emp.ExpirationDateUtc = DateTime.Now.AddYears(1);
            emp.CreateTime = DateTime.Now;
            emp.ApiToken = Guid.NewGuid().ToString();
            emp.WebToken = Guid.NewGuid().ToString();
            emp.EmployeeDetail = new EmployeeDetail()
            {
                EnglishName = "zhangsan" + rd.Next(99),
                CreateTime = DateTime.Now,
            };

            emp.EmployeeLogins.Add(new EmployeeLogin
            {
                CreateTime = DateTime.Now
            });


            var aaa2255 = _employeeContract.CreateEntity(emp, (e) => {
                if (string.IsNullOrWhiteSpace(e.BankCard))
                {
                    e.BankCard = "1000000" + rd.Next(1000, 9999);
                }
            });



        }

        /// <summary>
        /// 测试新增test
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Route("AddTest")]
        public IActionResult AddTest(string name)
        {
            Biz_Test tt = new Biz_Test();
            tt.Name = name; 
            tt.Phone = "15225074031";

            tt.TestStatus = EmployeeStatus.PendingStatus;

            tt.BirthDate = DateTime.Now;
            tt.LeaveDate = DateTime.Now.Date;
            tt.CreateTime = DateTime.Now;

            var result = _testContract.SaveEntity(tt);

            var list = _testContract.GetList();

            var aaa = tt.TestStatus.HasFlag(EmployeeStatus.WaitStatus);

            return Ok(list);
        }



        private void enumTest()
        {
            var aaa = EmployeeStatus.PendingStatus.ToDescription();
            var ccc = typeof(EmployeeStatus).ToEnumForDictionary();
        }
        private void AesTest()
        {
            var a = "123";
            var aaaa = SecurityHelper.Encrypt(a);
            var bbbb = SecurityHelper.Decrypt(aaaa);

            var filepath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/ldh.docx");
            var filepath2 = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/ldh2.docx");
            var filepath3 = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/ldh3.docx");

            filepath.CheckFileExists("ldhdd");
            SecurityHelper.EncryptFile(filepath, filepath2);
            SecurityHelper.DecryptFile(filepath2, filepath3); 
        }

    }
}
